package ch01.BitmapCollision
{
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.filters.GlowFilter;
    import flash.geom.Matrix;
    import flash.geom.Point;
    import flash.text.TextField;
    import flash.utils.getTimer;
    import flash.utils.setTimeout;
    
    import net.hires.debug.Stats;
    
    import tools.HitTest;
    import tools.Triangle;
    
    /**
     * 不规则物体碰撞测试3,HitTest.complexHitTestObject方法
     * @author sjp
     *
     */
    public class HitTest3 extends Sprite
    {
        private var tri1:Triangle;
        private var tri2:Triangle;
        private var isHit:Boolean = false;
        
        public function HitTest3()
        {
            stage.align = StageAlign.TOP_LEFT;
            stage.scaleMode = StageScaleMode.NO_SCALE;
            setTimeout(callLaterHandler, 500);
        }
        
        /**
         * 该函数需要延时处理，否则在IE6下，stage.stageWidth和stage.stageHeight为0，BitmapData创建会出现异常
         * */
        private function callLaterHandler(event:Event = null):void
        {
            // make two stars, add to stage
            tri1 = new Triangle(50);
            tri1.rotation = 30;
            addChild(tri1);
            tri2 = new Triangle(50);
            tri2.x = 200;
            tri2.y = 200;
            addChild(tri2);
            stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMoving);
            addChild(new Stats());
        }
        
        /**
         * 在构造函数内创建了两个BitmapData对象和两个星星，两个BitmapData对象没有放入Bitmap中，也就是没有加入到显示列表里， 而是直接加入了两个星星。
         * 名为star1的星星跟随鼠标移动。每当鼠标移动时，两个位图都用fillRect清空。结果就是两张完全透明的位图，然后分别 绘上对应的星星：
         * bmpd1.draw(star1, new Matrix(1,0,0,1, star1.x,star1.y)); bmpd2.draw(star2, new Matrix(1,0,0,1, star2.x,star2.y));
         * 绘制时采用了星星的位置作为矩阵(matrix)的偏移量。现在测试：
         * if(bmpd1.hitTest(new Point(), 255, bmpd2, new Point(), 255))
         * 因为BitmapData不在显示列表里，甚至都没在Bitmap中，加上两个星星又是同一坐标系，且被绘制在各自的相对位置上，所以不用去考虑任何坐标关系。只需传入默认情况下x和y都为0的Point即可。而透明阈值为255意味着两个星星不透明。
         * */
        private function onMouseMoving(event:MouseEvent):void
        {
            var time1:int = getTimer();
            tri1.x = mouseX;
            tri1.y = mouseY;
            isHit = HitTest.complexHitTestObject(tri1, tri2);
            if (isHit)
            {
                tri1.filters = [new GlowFilter()];
                tri2.filters = [new GlowFilter()];
            }
            else
            {
                tri1.filters = [];
                tri2.filters = [];
            }
            trace(getTimer() - time1);
        }
    }
}